import csv
import numpy as np

def readData():
    X = []
    y = []
    with open('Housing.csv') as f:
        rdr = csv.reader(f)
        # Skip the header row
        next(rdr)
        # Read X and y
        for line in rdr:
            xline = [1.0]
            xline.append(float(line[2]))
            for s in line[3:]:
                if s == 'yes':
                    xline.append(float(1))
                elif s == 'no':
                    xline.append(float(0))
                else:
                    xline.append(float(s))
            X.append(xline)
            y.append(float(line[1]))
    return (X,y)

x0,y0 = readData()
# Convert all but the last 10 rows of the raw data to numpy arrays
d = len(x0)-10
#np.array可视为矩阵
X = np.array(x0[:d])
#转置
y = np.transpose(np.array([y0[:d]]))

# Compute beta
#β = (XT X)-1 XT y
Xt = np.transpose(X)
print(Xt,X)
XtX = np.dot(Xt, X)
print(XtX)
Xty = np.dot(Xt, y)
beta = np.linalg.solve(XtX,Xty)
print(beta)

# Make predictions for the last 10 rows in the data set
for data, actual in zip(x0[d:], y0[d:]):
    x = np.array([data])
    prediction = np.dot(x, beta)
    print('prediction = '+str(prediction[0, 0])+' actual = '+str(actual))

#https://blog.csdn.net/lllone/article/details/83615931